package com.eapi.project.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.eapi.eapicommom.model.entity.InterfaceInfo;
import com.eapi.eapicommom.model.entity.User;
import com.eapi.project.annotation.AuthCheck;
import com.eapi.project.common.ResultUtils;
import com.eapi.project.constant.CommonConstant;
import com.eapi.project.exception.BusinessException;
import com.eapi.project.service.InterfaceInfoService;
import com.eapi.project.service.UserService;
import com.eapi.project.common.BaseResponse;
import com.eapi.project.common.DeleteRequest;
import com.eapi.project.common.ErrorCode;

import com.eapi.project.model.dto.comment.CommentAddRequest;
import com.eapi.project.model.dto.comment.CommentLikeRequest;
import com.eapi.project.model.dto.comment.CommentQueryRequest;
import com.eapi.project.model.dto.comment.CommentUpdateRequest;
import com.eapi.project.model.entity.Comment;
import com.eapi.project.model.vo.CommentVO;
import com.eapi.project.service.CommentService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * 帖子接口
 *
 * @author yupi
 */
@RestController
@RequestMapping("/comment")
@Slf4j
public class CommentController {

    @Resource
    private CommentService commentService;

    @Resource
    private UserService userService;

    @Resource
    private InterfaceInfoService interfaceInfoService;

    // region 增删改查

    /**
     * 创建
     *
     * @param commentAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addComment(@RequestBody CommentAddRequest commentAddRequest, HttpServletRequest request) {
        if (commentAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Comment comment = new Comment();
        BeanUtils.copyProperties(commentAddRequest, comment);
        InterfaceInfo interfaceInfo = interfaceInfoService.getById(commentAddRequest.getInterfaceInfoId());
        if (interfaceInfo == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"接口不存在");
        }
        // 设置接口的名词
        String interfaceInfoName = interfaceInfo.getName();
        comment.setInterfaceInfoName(interfaceInfoName);
        // 获取当前登录用户的id和姓名
        User loginUser = userService.getLoginUser(request);
        String userName = loginUser.getUserName();
        if(userName == null){
            comment.setUserName(loginUser.getUserAccount());
        }
        else{
            comment.setUserName(loginUser.getUserName());
        }
        comment.setUserId(loginUser.getId());

        // 校验
        commentService.validComment(comment, true);
        boolean result = commentService.save(comment);
        if (!result) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        // interface表中的评论数加一
        interfaceInfo.setComments(interfaceInfo.getComments()+1);
        interfaceInfoService.updateById(interfaceInfo);
        long newCommentId = comment.getId();
        return ResultUtils.success(newCommentId);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteComment(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Comment oldComment = commentService.getById(id);
        if (oldComment == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        //校验权限
        boolean permissionCheck = !oldComment.getUserId().equals(user.getId()) && !userService.isAdmin(request);

        // 仅本人或管理员可删除
        if (permissionCheck) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = commentService.removeById(id);
        // interface表中的评论数减一
        InterfaceInfo interfaceInfo = interfaceInfoService.getById(oldComment.getInterfaceInfoId());
        interfaceInfo.setComments(interfaceInfo.getComments()-1);
        interfaceInfoService.updateById(interfaceInfo);
        return ResultUtils.success(b);
    }

    /**
     * 更新
     *
     * @param commentUpdateRequest
     * @param request
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = "admin")
    public BaseResponse<Boolean> updateComment(@RequestBody CommentUpdateRequest commentUpdateRequest,
                                            HttpServletRequest request) {
        if (commentUpdateRequest == null || commentUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Comment comment = new Comment();
        BeanUtils.copyProperties(commentUpdateRequest, comment);
        // 参数校验
        commentService.validComment(comment, false);
        User user = userService.getLoginUser(request);
        long id = commentUpdateRequest.getId();
        // 判断是否存在
        Comment oldComment = commentService.getById(id);
        if (oldComment == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 仅本人或管理员可修改
        if (!oldComment.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = commentService.updateById(comment);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取
     *
     * @param interfaceInfoId
     * @return
     */
    @GetMapping("/get")
    public BaseResponse<List<CommentVO>> getCommentByInterfaceId(Long interfaceInfoId) {
        if(interfaceInfoId == null || interfaceInfoId <= 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"接口不存在");
        }
        QueryWrapper<Comment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("interfaceInfoId",interfaceInfoId);
        List<Comment> list = commentService.list(queryWrapper);
        List<CommentVO> commentVOList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            CommentVO commentVO = new CommentVO();
            Comment comment = list.get(i);
            Long userId = comment.getUserId();
            String userAvatar = userService.getById(userId).getUserAvatar();
            BeanUtils.copyProperties(comment,commentVO);
            commentVO.setUserAvatar(userAvatar);
            commentVOList.add(commentVO);
        }
        return ResultUtils.success(commentVOList);
    }

    /**
     * 获取列表（仅管理员可使用）
     *
     * @param commentQueryRequest
     * @return
     */
    @AuthCheck(mustRole = "admin")
    @GetMapping("/list")
    public BaseResponse<List<Comment>> listComment(CommentQueryRequest commentQueryRequest) {
        if(commentQueryRequest.getInterfaceInfoId().toString() == null){
            return null;
        }
        Comment commentQuery = new Comment();
        if (commentQueryRequest != null) {
            BeanUtils.copyProperties(commentQueryRequest, commentQuery);
        }
        QueryWrapper<Comment> queryWrapper = new QueryWrapper<>(commentQuery);
        List<Comment> commentList = commentService.list(queryWrapper);
        return ResultUtils.success(commentList);
    }

    /**
     * 分页获取列表
     *
     * @param commentQueryRequest
     * @param request
     * @return
     */
    @GetMapping("/list/page")
    public BaseResponse<Page<Comment>> listCommentByPage(CommentQueryRequest commentQueryRequest, HttpServletRequest request) {
        if(commentQueryRequest.getInterfaceInfoId().toString() == null){
            return null;
        }
        if (commentQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Comment commentQuery = new Comment();
        BeanUtils.copyProperties(commentQueryRequest, commentQuery);
        long current = commentQueryRequest.getCurrent();
        long size = commentQueryRequest.getPageSize();
        String sortField = commentQueryRequest.getSortField();
        String sortOrder = commentQueryRequest.getSortOrder();
        String content = commentQuery.getContext();
        // content 需支持模糊搜索
        commentQuery.setContext(null);
        // 限制爬虫
        if (size > 50) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        QueryWrapper<Comment> queryWrapper = new QueryWrapper<>(commentQuery);
        queryWrapper.like(StringUtils.isNotBlank(content), "content", content);
        queryWrapper.orderBy(StringUtils.isNotBlank(sortField),
                sortOrder.equals(CommonConstant.SORT_ORDER_ASC), sortField);
        Page<Comment> commentPage = commentService.page(new Page<>(current, size), queryWrapper);
        return ResultUtils.success(commentPage);
    }

    // endregion
    @PostMapping("/like")
    public BaseResponse<Boolean> likeComment(@RequestBody CommentLikeRequest commentLikeRequest, HttpServletRequest request) {
        Comment comment = commentService.getById(commentLikeRequest.getId());
        if (comment == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        comment.setLikes(comment.getLikes() + 1);
        boolean result = commentService.updateById(comment);
        return ResultUtils.success(result);
    }

}
